<template>
  <!-- 绑定邮箱 -->
  <div class="bind_container">
    <nut-form
      label-position="top"
      ref="formRef"
      :model-value="emailFormData"
      :rules="rules"
    >
      <nut-form-item :label="t('hall_Email')" prop="email">
        <div class="code_wrap">
          <nut-input
            v-model="emailFormData.email"
            :placeholder="t('empty_tips3')"
            type="text"
            :disabled="userInfo.email != ''"
            clearable
          />
          <nut-button class="send_code" @click="sendCode">{{ codeValue }}</nut-button>
        </div>
      </nut-form-item>
      <nut-form-item :label="t('home_page_smsCode')">
        <nut-input
          v-model="emailFormData.verify_code"
          :placeholder="t('home_page_enterSmsCode')"
          type="number"
        />
      </nut-form-item>
    </nut-form>

    <div :class="['submit_wrap',verifyTrue? '':'submit_wrap_1']">
      <nut-button class="submit"  @click="submit">
        {{ verifyTrue ? t("btn_label_next") : t("btn_label_bind") }}</nut-button
      >
    </div>
    <Toast v-model:visible="visible">{{ toast_value }}</Toast>
  </div>
</template>

<script setup lang="ts">
import { emailValidator } from "../validator";
import { ref, defineAsyncComponent } from "vue";
import { verifyEmail } from "@/utils/validateTools";
import { useI18n } from "vue-i18n";
import PKwebsocket from "@/lolo/Ws";
import { NetPacket } from "@/netBase/NetPacket";
import { IP } from "@/utils/useStoreMethods";
import { User } from "@/store/user";
import pinia from "@/store";
import { storeToRefs } from "pinia";
import { useRouter } from "vue-router";
import { aaa, bbb, getDeviceId, getRandomSign } from "@/net/Utils";

const Toast = defineAsyncComponent(() => import("@/components/Toast.vue"));

const UserStore = User(pinia);
const emits = defineEmits(["verifyClick"]);
const props = defineProps({
  verifyTrue: {
    type: Boolean,
    default: false,
  },
});
const formRef: any = ref(null);
const { info: userInfo, roleInfo } = storeToRefs(UserStore);
const { t } = useI18n();
const visible = ref(false);

const toast_value = ref("");
const router = useRouter();
const codeValue = ref(t("get_verification_code"));
const rules = {
  email: [{ validator: emailValidator }],
};

const times = ref(60);

const emailFormData: any = ref({
  email: userInfo.value.email || "",
  verify_code: "",
});

//  发送验证码
const sendCode = () => {
  if (!emailFormData.value.email) {
    visible.value = true;
    toast_value.value = t("home_page_enterEmail");
    return;
  }

  if (times.value < 60) {
    return;
  }
  if (verifyEmail(emailFormData.value.email)) {
    const query = NetPacket.req_get_email_verification_code();
    query.email = emailFormData.value.email;
    query.operate_type = props.verifyTrue ? 4 : 2;
    PKwebsocket.instance.send(query, true, {
      callbackName: 'msg_notify_get_email_verification_code',
      callback: notify_result
    })
  } else {
    visible.value = true;
    toast_value.value = t("home_page_emailIncorrect");
  }
};

// 验证码回执

const notify_result = (rs: any) => {
  if (rs.code == 1) {
    visible.value = true;
    toast_value.value = t("verification_code_sent_success");
    let timeInterval = setInterval(() => {
      times.value--;
      codeValue.value = String(times.value);
      if (times.value <= 0) {
        clearInterval(timeInterval);
        codeValue.value = t("get_verification_code");
        times.value = 60;
      }
    }, 1000);
  }
};

// 提交
const submit = () => {
  formRef.value?.validate().then(async ({ valid, errors }: any) => {
    if (valid) {
      if (props.verifyTrue) {
        emits("verifyClick", emailFormData.value);
      } else {
        const id = await getDeviceId();
        const query = NetPacket.req_bind_modify_email();
        query.email = emailFormData.value.email;
        query.operate_type = 1;
        query.captcha = emailFormData.value.verify_code;
        query.aaa = aaa.toString();
        query.bbb = bbb;
        query.sign = getRandomSign(id);
        query.ip = await IP();
        query.ip_error = "0";
        query.password = "";
        query.device_model = "";
        query.channel_id = 0;
        query.username = userInfo.value?.full_name as string;
        query.agent_id = Number(roleInfo.value.id);
        PKwebsocket.instance.send(query, true, {
          callbackName: 'msg_notify_bind_modify_email',
          callback: notify_bind_result
        })
      }
    } else {
      console.warn("error:", errors);
    }
  });
};
// 提交回执
const notify_bind_result = (rs: any) => {
  if (rs.code == 1) {
    visible.value = true;
    toast_value.value = t("phone_tip_3");
    setTimeout(() => {
      router.push("/securitySettings");
    }, 1500);
  }else{
    visible.value = true;
    toast_value.value = t(rs.message);
  }
};

</script>

<style lang="scss" scoped>
@import url(../style.scss);
.submit_wrap_1{
  bottom: 50px !important;
  left: 0;
}

</style>
